﻿using Flame.Dlr;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Flame.Controls
{
    public class ScripterLoaderControl : TabPage
    {
        public class CompilerReadyEventArgs : EventArgs
        {
            public Manager CompilersManager { get; set; }
        }
        public class DocChangedEventArgs : EventArgs
        {
            public string DocPath { get; set; }
        }

        //public event EventHandler<CompilerReadyEventArgs> OnCompilerReady;
        public event EventHandler<Flame.Controls.TextInputWithInfo.TextInputPropertyChangedEventArgs> TextInputPropertyChanged;
        //public event EventHandler<DocChangedEventArgs> OnDocChanged;

        public bool AutoSaveOnClose { get; set; }
        internal enum SaveResult { Saved, Notsaved, Cancelled };
        public ScripterControl ScripterControl { get; set; }


        string _docPath = null;
        public string DocPath 
        {
            get
            {
                return _docPath;
            }
            private set
            {
                _docPath = value;
                if (DocPath != null)
                    Text = new System.IO.FileInfo(DocPath).Name;
                else
                    Text = "new";
                /*if (OnDocChanged != null)
                    OnDocChanged(this, new DocChangedEventArgs() { DocPath = DocPath });*/
            }
        }

        public ScripterLoaderControl(TextInputCreator textInputCreator, string defaultLanguage = "None")
        {
            //DocPath = docPath;

            ScripterControl = new ScripterControl(textInputCreator, defaultLanguage);
            ScripterControl.TextInputPropertyChanged += (s, e) => 
            { 
                if (TextInputPropertyChanged != null) 
                    TextInputPropertyChanged(this, e); 
            };

            AutoSaveOnClose = true;

            SuspendLayout();


            Controls.Add(ScripterControl.VerticalPanelScroll);
            Text = "new";
            ResumeLayout();
            //Load += ScripterLoaderControl_Load;
        }

  

        void _cellsToFile()
        {
            File.WriteAllText(DocPath, CellManager.ToText(ScripterControl.Cells));
        }
        void _fileToCells()
        {
            ScripterControl.Cells = CellManager.FromText(File.ReadAllLines(DocPath));
        }


        bool _saveDialog()
        {
            var dialog = new SaveFileDialog();
            dialog.CheckPathExists = true;
            var result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                return SaveFile(dialog.FileName);
            }
            return false;
        }
        public void SaveDialog()
        {
            if (DocPath != null)
                SaveFile();
            else
                _saveDialog();
        }

        /*public bool ExportTxtDialog()
        {
            var dialog = new SaveFileDialog();
            dialog.CheckPathExists = true;
            var result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                return SaveFileTxt(dialog.FileName);
            }
            return false;
        }*/
        public bool SaveAsDialog()
        {
            return _saveDialog();
        }


        /*public void LoadFileTxt(string filepath)
        {
            try
            {

               // ScripterControl.Cells = from x in ScriptHelper.TxtToScripts(File.ReadAllLines(filepath)) select new Cell(x) { Auto = false };
            }
#if DEBUG
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message);
                System.Windows.Forms.MessageBox.Show("Cannot import the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
#else
            catch 
            {
                System.Windows.Forms.MessageBox.Show("Cannot open the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
#endif
        }*/

        public void LoadFile(string docPath)
        {
            DocPath = docPath;
            if(DocPath != null)
                LoadFile();
        }

        void LoadFile()
        {
            try
            {
                _fileToCells();
                
            }
#if DEBUG
            catch (Exception e)
            {
                System.Windows.Forms.MessageBox.Show(e.Message);
                System.Windows.Forms.MessageBox.Show("Cannot open the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
#else
            catch 
            {
                System.Windows.Forms.MessageBox.Show("Cannot open the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
#endif
        }



        SaveResult CheckIsSaved()
        {
            SaveResult result = ScripterControl.HasStateChanged ? SaveResult.Notsaved : SaveResult.Saved;
            if (result != SaveResult.Saved)
            {
                var resultT = MessageBox.Show("Do you want to save changes before open a new document?", "Open", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                if (resultT == System.Windows.Forms.DialogResult.Cancel)
                    result = SaveResult.Cancelled;
                else if (resultT == System.Windows.Forms.DialogResult.No)
                    result = SaveResult.Notsaved;
                else
                {
                    if (DocPath != null)
                    {
                        _cellsToFile();
                        result = SaveResult.Saved;
                    }
                    else
                        result = _saveDialog() ? SaveResult.Saved : SaveResult.Cancelled;
                }
            }
            return result;
        }



        /*public bool SaveFileTxt(string filepath)
        {
            try
            {
                //File.WriteAllText(filepath, ScriptHelper.ScriptsToTxt((from x in ScripterControl.Cells select (Script)x).ToList()));
            }
            catch (Exception)
            {
                System.Windows.Forms.MessageBox.Show("Cannot save the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }*/

        public bool SaveFile(string docPath)
        {
            DocPath = docPath;
            return SaveFile();
        }
        public bool SaveFile()
        {
            try
            {
                _cellsToFile();
                ScripterControl.SaveState();
            }
            catch (Exception)
            {
                System.Windows.Forms.MessageBox.Show("Cannot save the file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
            return true;
        }

        public bool AskForClose()
        {
            bool letclose = false;
            if (ScripterControl.HasStateChanged)
            {
                if (AutoSaveOnClose && DocPath != null)
                {
                    _cellsToFile();
                    letclose = true;
                }

                if (!letclose && CheckIsSaved() != ScripterLoaderControl.SaveResult.Cancelled)
                {
                    letclose = true;
                }
            }
            else
                letclose = true;

           return letclose;
        }


    }
}
